﻿using AutoMapper;
using MediatR;
using Microsoft.CodeAnalysis;
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Api.Application.Command.DeviceManage.Project;
using ProduceBasicData.Domain.DeviceManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using System.Transactions;

namespace ProduceBasicData.Api.Application.Handler.DeviceManage.Project
{
    /// <summary>
    /// 项目表单录入请求处理器
    /// </summary>
    public class CreateProjectFormHandler : IRequestHandler<CreateProjectFormCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProjectForm> _projectFormRepository;
        private readonly IBaseRespository<ProjectFormRelation> _projectFormRelationRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="projectFormRepository"></param>
        /// <param name="projectFormRelationRepository"></param>
        /// <param name="mapper"></param>
        public CreateProjectFormHandler(IBaseRespository<ProjectForm> projectFormRepository, IBaseRespository<ProjectFormRelation> projectFormRelationRepository, IMapper mapper)
        {
            _projectFormRepository = projectFormRepository;
            _projectFormRelationRepository = projectFormRelationRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理项目表单录入请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(CreateProjectFormCommand request, CancellationToken cancellationToken)
        {
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    //将命令转换为领域模型
                    var ProjectForm = _mapper.Map<ProjectForm>(request);
                    //判断项目表单是否存在
                    var ProjectFormExist = await _projectFormRepository.GetAll().AnyAsync(x => x.FormName == ProjectForm.FormName, cancellationToken);
                    if (ProjectFormExist)
                    {
                        return new ApiResult<int>
                        {
                            Code = ApiEnum.Failed,
                            Msg = "项目表单已存在"
                        };
                    }
                    //保存项目表单
                    var formId = await _projectFormRepository.AddAndGetIdAsync(ProjectForm);
                    if (formId <= 0)
                    {
                        return new ApiResult<int>
                        {
                            Code = ApiEnum.Failed,
                            Msg = "项目表单录入失败"
                        };
                    }

                    var relations = new List<ProjectFormRelation>();
                    foreach(int projectId in request.ProjectIds)
                    {
                        relations.Add(new ProjectFormRelation
                        {
                            FormId = formId,       // 关联新增的项目表单ID
                            ProjectId = projectId,    // 关联选中的检验项目ID
                            CreateName = request.CreateName,
                            CreateTime = DateTime.Now
                        });
                    }
                    if (relations.Any())
                    {
                        await _projectFormRelationRepository.AddRangeAsync(relations);
                    }

                    // 5. 提交事务（所有操作生效）
                    transaction.Complete();

                    return new ApiResult<int>
                    {
                        Data = formId,
                        Code = ApiEnum.Success,
                        Msg = "项目表单及关联数据录入成功"
                    };
                }
                catch (Exception ex)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = ex.Message
                    };
                }
            }
        }
    }
}
